<template>
  <div class="app-container">
    <!--  @click="onGroupAdd" -->
    <el-button
      type="primary"
      size="mini"
      icon="el-icon-plus"
      style="margin-bottom: 10px"
      @click="onGroupAdd"
      >添加模板组</el-button
    >
    <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
      <el-tab-pane
        v-for="(item, index) in groupData"
        :key="item.id"
        :name="`${item.id}`"
        :label="item.groupName"
      >
        <span slot="label">
          {{ item.groupName }}
          <el-dropdown
            v-show="item.id === currentTab.id"
            trigger="click"
            style="margin-left: 5px"
            @command="(command) => handleCommand(command, item, index)"
          >
            <span class="el-dropdown-link">
              <el-tooltip placement="top" content="更多操作" :open-delay="500">
                <a class="el-icon-setting el-icon--right"></a>
              </el-tooltip>
            </span>
            <!-- <el-dropdown-menu slot="dropdown">
              <el-dropdown-item
                icon="el-icon-edit"
                :command="onGroupInfoUpdate(item)"
                >修改</el-dropdown-item
              >
              <el-dropdown-item
                icon="el-icon-delete"
                :command="onGroupInfoDelete"
                >删除</el-dropdown-item
              >
            </el-dropdown-menu> -->
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-edit" command="edit"
                >修改</el-dropdown-item
              >
              <el-dropdown-item icon="el-icon-delete" command="delete"
                >删除</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </span>
      </el-tab-pane>
      <el-button
        type="text"
        size="mini"
        icon="el-icon-plus"
        style="margin-bottom: 10px"
        @click="onAdd"
        >新增模板</el-button
      >
      <!-- <el-button type="text" size="mini" icon="el-icon-upload2" style="margin-bottom: 10px;" @click="onImportTemplates">批量导入</el-button> -->
      <el-button
        type="text"
        size="mini"
        icon="el-icon-download"
        style="margin-bottom: 10px"
        @click="downloadTemplates"
        >导出模板</el-button
      >
      <el-table :data="tableData" border highlight-current-row>
        <el-table-column prop="name" label="模板名称" width="200" />
        <el-table-column prop="fileName" label="文件名称" />
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="onTableUpdate(scope.row)"
              >修改</el-button
            >
            <el-button type="text" size="mini" @click="onTableCopy(scope.row)"
              >复制</el-button
            >
            <el-button type="text" size="mini" @click="onTableDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-tabs>
    <el-dialog
      title="批量导入模板"
      :visible.sync="importDialogVisible"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      @closed="onImportDialogClosed"
    >
      <el-upload
        v-if="!importLoading"
        drag
        multiple
        accept=".txt,.vm"
        action="http://xx.nothing"
        :limit="20"
        :show-file-list="false"
        :http-request="uploadTemplates"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <el-table v-if="importLoading" :data="importFiles" style="width: 100%">
        <el-table-column prop="name" label="文件" width="180"></el-table-column>
        <el-table-column prop="state" label="状态"></el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog
      :title="titleName"
      :visible.sync="dialoVisible"
      v-if="dialoVisible"
      width="52%"
    >
      <el-form :model="ruleForm" ref="ruleForm" :inline="true">
        <el-form-item
          label="请输入组名称:"
          prop="groupName"
          label-width="120px"
          :rules="[
            {
              required: true,
              pattern: /^.{1,64}$/,
              message: '组名称不能为空且长度在64以内',
              trigger: 'blur',
            },
          ]"
          class="groupClass"
          style="display: flex"
        >
          <el-input v-model="ruleForm.groupName"></el-input>
        </el-form-item>
        <div>
          <el-button
            type="primary"
            v-if="ruleForm.dependency.length == 0"
            @click="handleAddBody"
            >新增模板所需依赖</el-button
          >
          <div v-else class="tempClass" style="display: flex">
            <div class="tempyilai">
              模板所需依赖
              <el-popover
                placement="right"
                width="200"
                trigger="hover"
                content="请填写公有库依赖，若需要私有库，请联系管理员"
              >
                <span slot="reference" style="color: red; margin-right: 5px"
                  >?</span
                >
              </el-popover>
              :
            </div>
            <div>
              <div
                v-for="(item, index) in ruleForm.dependency"
                :key="index"
                class="flexClass"
              >
                <el-form-item
                  label="groupId："
                  :prop="`dependency.${index}.groupId`"
                  :rules="[
                    {
                      required: true,
                      message: '请输入groupId',
                      trigger: 'blur',
                    },
                  ]"
                  label-width="90px"
                >
                  <el-input
                    v-model.trim="item.groupId"
                    clearable
                    style="width: 150px"
                  />
                </el-form-item>
                <el-form-item
                  label="artifactId："
                  :prop="`dependency.${index}.artifactId`"
                  class="artiClassfactId"
                  :rules="[
                    {
                      required: true,
                      message: '请输入artifactId',
                      trigger: 'blur',
                    },
                  ]"
                  label-width="100px"
                >
                  <el-input
                    v-model.trim="item.artifactId"
                    clearable
                    style="width: 150px"
                  />
                </el-form-item>
                <el-form-item
                  label="version："
                  :prop="`dependency.${index}.version`"
                  label-width="90px"
                  :rules="[
                    {
                      required: true,
                      message: '请输入version',
                      trigger: 'blur',
                    },
                  ]"
                >
                  <el-input
                    v-model.trim="item.version"
                    clearable
                    style="width: 150px"
                  />
                </el-form-item>
                <div style="margin-top: 12px">
                  <i
                    class="el-icon-circle-plus"
                    style="
                      font-size: 20px;
                      color: #409eff;
                      cursor: pointer;
                      margin-top: 5px;
                    "
                    @click="handleAddBody"
                  ></i>
                  <i
                    class="el-icon-remove"
                    style="
                      font-size: 20px;
                      color: #409eff;
                      cursor: pointer;
                      margin-top: 5px;
                    "
                    @click="handleReduceBody(index)"
                  ></i>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialoVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import JSZip from "jszip";
import { saveAs } from "file-saver";
import { groupList, templatesList } from "@/api/codeManagement"; // 请求数据
const CUR_GROUP_ID_KEY = "gen.cur.groupid";
import { codeGroupAdd, codeGroupUpdate } from "@/api/article";
export default {
  data() {
    return {
      dialoVisible: false,
      ruleForm: {
        groupName: "",
        dependency: [],
      },
      titleName: "增加模板组",
      activeName: "",
      tableData: [],
      groupData: [],
      currentTab: { id: 0 },
      importDialogVisible: false,
      importLoading: false,
      importFiles: [],
    };
  },
  created() {
    this.reload();
  },
  methods: {
    reload() {
      const groupId = this.getAttr(CUR_GROUP_ID_KEY);
      if (groupId) {
        this.currentTab.id = parseInt(groupId);
      }
      this.loadGroup();
    },
    async loadGroup() {
      const res = await groupList(this.listQuery);
      if (!res) {
        return;
      }
      this.groupData = res.data;
      let id = this.currentTab.id;
      if (!id && this.groupData.length > 0) {
        id = this.groupData[0].id;
      }
      if (id) {
        this.selectTab(id);
      }
    },
    selectTab(id) {
      for (const group of this.groupData) {
        if (group.id === id) {
          this.currentTab = group;
          break;
        }
      }
      this.loadTable(id);
      console.log(id, 3000);
    },
    async loadTable(groupId) {
      this.setAttr(CUR_GROUP_ID_KEY, groupId);
      this.activeName = `${groupId}`;
      const res = await templatesList(groupId);
      if (!res) {
        return;
      }
      this.tableData = res.data;
    },
    handleClick(tab) {
      const id = parseInt(tab.name);
      if (id) {
        this.selectTab(parseInt(id));
      }
    },
    onTableUpdate: function (row) {
      this.goRoute(`edit?id=${row.id}`);
    },
    onTableCopy: function (row) {
      let currentGroup = this.currentTab;
      this.groupTitle = `确认要复制【${row.name}】吗？`;
      this.$prompt("请输入复制后的模板名称", "复制模板", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValue: row.name + " Copy",
        inputPattern: /^.{1,64}$/,
        inputErrorMessage: "不能为空且长度在64以内",
      })
        .then(({ value }) => {
          if (value === row.name) {
            this.tip("名称不能重复", "error");
            return;
          }
          const data = {
            name: value,
            id: row.id,
            groupName: currentGroup.groupName,
            groupId: currentGroup.groupId,
          };
          this.post("/template/code/copy", data, (resp) => {
            this.reload();
          });
        })
        .catch(() => {});
    },
    onTableDelete: function (row) {
      this.confirm(`确认要删除【${row.name}】吗？`, function (done) {
        this.post("/template/code/del", row, function () {
          done();
          this.tip("删除成功");
          this.reload();
        });
      });
    },
    onAdd: function () {
      //this.goRoute(`edit/0?groupId=${this.currentTab.id}`)
      this.goRoute(`edit?id=0&groupId=${this.currentTab.id}`);
    },
    // group
    // onGroupInfoUpdate(item) {
    //   this.onGroupUpdate(this.currentTab);
    // },
    // onGroupInfoDelete() {
    //   this.onGroupDelete(this.currentTab);
    // },
    // onGroupUpdate: function (row) {
    //   this.$prompt("请输入组名称", "修改模板组", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     inputValue: row.groupName,
    //     inputPattern: /^.{1,64}$/,
    //     inputErrorMessage: "不能为空且长度在64以内",
    //   })
    //     .then(({ value }) => {
    //       const data = {
    //         id: row.id,
    //         groupName: value,
    //       };
    //       this.post("/template/codeGroup/update", data, (resp) => {
    //         this.reload();
    //       });
    //     })
    //     .catch(() => {});
    // },
    // onGroupDelete: function (row) {
    //   this.confirm(`确认要删除【${row.groupName}】吗？`, function (done) {
    //     this.post("/template/codeGroup/del", row, function () {
    //       done();
    //       this.tip("删除成功");
    //       this.currentTab.id = 0;
    //       this.reload();
    //     });
    //   });
    // },
    handleCommand(command, item, index) {
      if (command == "edit") {
        this.titleName = "修改模板组";
        this.dialoVisible = true;
        this.ruleForm = JSON.parse(JSON.stringify(item));
        this.ruleForm.dependency = item.dependency
          ? JSON.parse(item.dependency)
          : [];
      } else if (command == "delete") {
        this.confirm(`确认要删除【${item.groupName}】吗？`, function (done) {
          this.post("/template/codeGroup/del", { id: item.id }, function () {
            done();
            this.tip("删除成功");
            this.currentTab.id = 0;
            this.reload();
          });
        });
      }
    },
    onGroupAdd() {
      // this.groupTitle = "增加模板组";
      // this.$prompt("请输入组名称", "增加模板组", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   inputValue: "",
      //   inputPattern: /^.{1,64}$/,
      //   inputErrorMessage: "不能为空且长度在64以内",
      // })
      //   .then(({ value }) => {
      //     const data = {
      //       groupName: value,
      //     };
      //     this.post("/template/codeGroup/add", data, (resp) => {
      //       this.currentTab = resp.data;
      //       this.reload();
      //     });
      //   })
      //   .catch(() => {});
      this.titleName = "增加模板组";
      this.dialoVisible = true;
      this.ruleForm = {
        groupName: "",
        dependency: [],
      };
    },

    onImportTemplates() {
      this.importFiles = [];
      this.importLoading = false;
      this.importDialogVisible = true;
    },
    onImportDialogClosed() {
      if (this.currentTab) {
        this.loadTable(this.currentTab.id);
      }
    },
    uploadTemplates(target) {
      this.importLoading = true;
      const file = target.file;
      this.importFiles.push({
        name: file.name,
        state: "上传中...",
      });
      const reader = new FileReader();
      reader.readAsText(file);
      reader.onloadend = async () => {
        let content = reader.result;
        let templateName = file.name;
        let splitIdx = templateName.lastIndexOf(".");
        if (splitIdx !== -1) {
          templateName = templateName.substring(0, splitIdx);
        }
        let data = {
          groupId: this.currentTab.id,
          groupName: this.currentTab.groupName,
          name: templateName,
          content: content,
        };
        await this.saveTemplate(data);
        this.importFiles.forEach((item) => {
          if (item.name === file.name) {
            item.state = "成功";
          }
        });
      };
      return true;
    },
    saveTemplate(data) {
      const uri = "/template/save";
      this.post(uri, data);
    },
    downloadTemplates() {
      const folder = this.currentTab.groupName;
      const filename = folder + ".zip";
      const zip = new JSZip();
      const folderZip = zip.folder(folder);
      this.tableData.forEach((row) => {
        folderZip.file(row.name + ".vm", row.content);
      });
      // 下载
      zip.generateAsync({ type: "blob" }).then(function (content) {
        // see FileSaver.js
        saveAs(content, filename);
      });
    },
    handleAddBody() {
      this.ruleForm.dependency.push({
        groupId: "",
        artifactId: "",
        version: "",
      });
    },
    handleReduceBody(index) {
      this.ruleForm.dependency.splice(index, 1);
    },
    submitForm() {
      this.$refs["ruleForm"].validate(async (valid) => {
        if (valid) {
          const forms = JSON.parse(JSON.stringify(this.ruleForm));
          forms.dependency = JSON.stringify(this.ruleForm.dependency);
          if (this.ruleForm.id) {
            const res = await codeGroupUpdate(forms);
            if (res?.code === 200) {
              this.dialoVisible = false;
              this.$message({
                message: "修改成功",
                type: "success",
              });
              this.reload();
            }
          } else {
            const res = await codeGroupAdd(forms);
            if (res?.code === 200) {
              this.dialoVisible = false;
              this.$message({
                message: "新增成功",
                type: "success",
              });
              this.currentTab = res.data;
              this.reload();
            }
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.flexClass {
  display: flex;
  ::v-deep .el-form-item {
    display: flex;
    align-items: center;
  }
}
.groupClass {
  ::v-deep .el-form-item__content {
    width: 84%;
  }
}
.tempClass {
  ::v-deep .el-form-item__content {
    margin-top: 13px !important;
  }
  ::v-deep .el-form-item__label {
    display: flex !important;
    align-items: center !important;
  }
}
.tempyilai {
  display: flex;
  align-items: center;
  padding-left: 6px;
  padding-bottom: 13px;
  font-weight: bolder;
  margin-right: 10px;
}
</style>
